/*
 * Copyright (c) GoKeep by gokeep.org. 2022-2023. All rights reserved
 */
package org.gokeep.communication.component;

import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.gokeep.common.document.HistoryMessage;
import org.gokeep.common.util.DateUtil;
import org.gokeep.communication.proto.ChatProto;
import org.gokeep.communication.proto.ChatRequestProto;
import org.gokeep.communication.proto.MessageProto;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;

@Component
public class HistoryMessageComponent {
    @Resource
    private MongoTemplate mongoTemplate;

    /**
     * 创建消息历史记录
     * @param historyMessage
     */
    public void create(HistoryMessage historyMessage, String collectionName) {
        mongoTemplate.insert(historyMessage, collectionName);
    }

    /**
     * 创建消息历史记录
     * @param historyMessage
     */
    public void create(HistoryMessage historyMessage) {
        String collectionName = HistoryMessage.COLLECTION_NAME_TEMP.formatted(DateUtil.getMongoCollectionSuffixWithNow());
        this.create(historyMessage, collectionName);
    }

    /**
     * 根据当前时间获取集合名称
     * @return
     */
    public String getCollectionNameByNow(){
        return getCollectionNameByTime(DateUtil.getMongoCollectionSuffixWithNow());
    }

    /**
     * 获取集合名称
     * @param time
     * @return
     */
    public String getCollectionNameByTime(String time){
        return HistoryMessage.COLLECTION_NAME_TEMP.formatted(time);
    }

    /**
     * 根据ChatRequest创建历史记录
     * @param message
     */
    public void create(MessageProto.Message message) {
        HistoryMessage historyMessage = generateHistoryMessage(message);
        create(historyMessage);
    }

    /**
     * 生成历史消息
     * @param message
     */
    @SneakyThrows
    public HistoryMessage generateHistoryMessage(MessageProto.Message message) {
        ChatRequestProto.ChatRequest clientChatMessage = ChatRequestProto.ChatRequest.parseFrom(message.getData());
        ChatProto.Chat chat =  clientChatMessage.getChat();
        return new HistoryMessage()
                .setFrom(chat.getFrom())
                .setTo(chat.getTo())
                .setGroupMessage(StringUtils.isNotBlank(chat.getGroupId()))
                .setGroupId(chat.getGroupId())
                .setSerializeNo(message.getSerializeNo())
                .setTimestamp(DateUtil.now())
                .setMessage(message.toByteArray());
    }
}